<?php

namespace App\Http\Controllers\Home;

use App\Models\Home\Comment;
use App\Models\Home\Weibo;
use App\Models\RTresult;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class CommentController extends Controller
{
    public function index(Request $request)
    {
        //一条微博的所有评论
        $weibo_id = $request->weibo_id;
        $rt_result = new RTresult();
        $comments = Comment::join('user_infos', 'comments.user_id', '=', 'user_infos.user_id')
            ->select('comments.*', 'user_infos.user_id', 'user_infos.nickname', 'user_infos.avatar')
            ->where('comments.weibo_id', $weibo_id)
            ->limit(10)
            ->orderBy('created_at', 'desc')
            ->get();
        if ($comments) {
            $rt_result->status = true;
            $rt_result->message = $comments;
            return $rt_result->toJson();
        }
    }

    public function store(Request $request)
    {
        //发表评论
        $rt_result = new RTresult();
        $comment = new Comment();
        $comment->user_id = $request->user_id;
        $comment->weibo_id = $request->weibo_id;
        $comment->content = $request->comment_content;
        $comment->created_at = getTimeFormat();
        if ($comment->save()) {
            //对应微博评论数+1
            Weibo::find($request->weibo_id)->increment('comment_num');
            $rt_result->status = true;
            $rt_result->message = $comment->id;
            return $rt_result->toJson();
        }
    }
}
